<?php

namespace App\Admin\Controllers\Shop;

use App\Admin\Actions\Extensions\Shop\ShopContactButton;
use App\Admin\Actions\Grid\GoodsTransferAction;
use App\Admin\Renderable\QuestionRender;
use App\Lib\Uploads\UploadHandler;
use App\Models\Shop\WxShopCart;
use App\Models\Shop\WxShopContact;
use App\Models\User\WxUser;
use App\Models\WxQuestion;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use DateTime;
use Dcat\Admin\Actions\Action;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Shop\WxShopClassify;
use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopGoodsProduct;
use App\Models\Shop\WxShopService;
use Dcat\Admin\Widgets\Tooltip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class WxShopGoodsController extends AdminController
{

    public function goods(Request $request)
    {
        $q = $request->get('q');
        $admin_user = Admin::user();
        if($admin_user->isAdministrator()){
            return WxShopGoods::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
        }else{
            if(_empty_($admin_user->uid)){
                return WxShopGoods::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
            }else{
                return WxShopGoods::where('user_id', $admin_user->uid)->where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
            }
        }
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $admin_user = Admin::user();
        $classfyids = WxShopClassify::where('depth', 3)->pluck('name', 'id')->toArray();
        $classfyids[0] = '未分类';
        $app_coin_name = Settings::get('app_coin_name', '硬币');
        return Grid::make(new WxShopGoods(), function (Grid $grid) use ($classfyids, $app_coin_name, $admin_user){
            global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
            $grid->simplePaginate();

            if(!$admin_user->isAdministrator()){
                if(_empty_($admin_user->uid)){
                    $grid->model()->where('id', '<', -1);
                }else{
                    $grid->model()->where('user_id', $admin_user->uid);
                }
            }
            $grid->quickSearch(['id', 'name'])->placeholder('搜索商品ID，名字...');
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('user', '商家')->display(function ($v){
                if(_empty_($v)){
                    return '系统自营';
                }
                return '<a href="'.admin_url('/users?id='.$v->id).'" target="_blank"><img src="'.$v->user_avatar.'" style="width: 30px; height: 30px;margin-right: 10px; border-radius: 50%;">'.$v->user_name. '</a>';
            });
            $grid->column('name')->limit(20);
            $grid->column('type')->using(FieldUtils::getShopGoodTypes())->sortable();
//            $grid->column('pic');
//            $grid->column('tag');
//            $grid->column('intro');
            $grid->column('vip_price')->display(function ($v) use ($app_coin_name){
                if($this->credit_type == 1){
                    return '￥'.$v;
                }else{
                    return $v.$app_coin_name;
                }
            })->sortable();
            $grid->column('price')->display(function ($v) use ($app_coin_name){
                if($this->credit_type == 1){
                    return '￥'.$v;
                }else{
                    return $v.$app_coin_name;
                }
            })->sortable();
//            $grid->column('content');
            $grid->column('views')->sortable()->editable();
            $grid->column('buys')->sortable()->editable();
            $grid->column('can_purchase_times', '限购次数')->sortable()->editable();
            $grid->column('rest_stock', '剩余库存')->display(function (){
               return WxShopGoodsProduct::where('goods_id', $this->id)->sum('stock');
            });
//            $grid->column('sku');

//            $grid->column('service_id');
            $grid->column('sort')->editable();
//            $grid->column('is_inspiration','灵感')->switch()->sortable();
            $grid->column('state')->switch()->sortable();
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $grid->column('classify_id')->sortable()->select($classfyids);
                $grid->column('collect_from_url')->display(function ($v){
                    if(_empty_($v)){
                        return '';
                    }
                    return '<a href="'.$v.'" target="_blank">链接</a>';
                });
            }
//            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) use ($classfyids){
                $filter->equal('id');
                $filter->equal('type')->multipleSelect(FieldUtils::getShopGoodTypes());
//                $filter->equal('classify_id')->multipleSelect($classfyids);
                $filter->like('name');
                $filter->equal('classify_id')->multipleSelect($classfyids);
            });
            $grid->batchActions(function ($batch) {
                $batch->add(new GoodsTransferAction());
            });

            global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $grid->tools([
                    new ShopContactButton(),
                ]);
            }
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxShopGoods(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('type');
//            $show->field('pic');
//            $show->field('tag');
            $show->field('intro');
            $show->field('vip_price');
            $show->field('price');
            $show->field('credit_type');
            $show->field('content');
            $show->field('views');
            $show->field('buys');
            $show->field('sort');
            $show->field('sku');
            $show->field('guest_present');
            $show->field('service_time_start');
            $show->field('service_time_end');

            $show->field('url');
            $show->field('download_version');
            $show->field('question_id');
            $show->field('can_purchase_times');
            $show->field('users_ledger');
            $show->field('classify_id');
//            $show->field('service_id');
            $show->field('state');
            $show->field('collect_from_url');
            $show->field('last_sales_at');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $app_coin_name = Settings::get('app_coin_name', '硬币');
        return Form::make(new WxShopGoods(), function (Form $form) use ($app_coin_name){
            global $__MINI_GLOBAL_IS_ADMIN_SUPER__, $__MINI_GLOBAL_PAYCODE_23__,$__MINI_GLOBAL_CURRENT_USER_ID__;
            $modle = $form->model();

            $res11 = __system__paycode__tip__(11);
            Tooltip::make('.mini_global_admin_open_not_support_tip')
                ->bottom()
                ->title($res11['tip']);
            $form->display('id');
            $form->text('name','商品名称')->required();
            if($form->isCreating()){
                $form->radio('credit_type', '货币')->options([ 0=> $app_coin_name, 1 => '余额/人民币'])->default(1)->required();
            }else{
                $form->html(function () use ($modle, $app_coin_name){
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">编辑模式不可更改货币类型，当前商品货币为：<span style="color: red;">'.($modle->credit_type == 1 ? '余额/人民币' : $app_coin_name).'</span></div>';
                }, '');
            }
            $form->text('vip_price','商品VIP价格')->required();
            $form->text('price','商品价格')->required();

            $form->textarea('intro','商品介绍');

            $options = AdminUtils::get_admin_user_shop_classifys();
            if(_empty_($options)){
                $form->html(function () use ($modle, $app_coin_name, $__MINI_GLOBAL_IS_ADMIN_SUPER__){
                    if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                        return '<div style="background-color: transparent;color: #414750;padding: 10px;border-radius: 5px;color: red;">!!! 当前没有第三层级的商品分类，无法新增商品</div>';
                    }else{
                        return '<div style="background-color: transparent;color: #414750;padding: 10px;border-radius: 5px;color: red;">!!! 当前后台账号无绑定的店铺id，无法新增商品，可联系超级管理员将你的后台账号角色变更为：商城管理员（标识：enterprise_admin）</div>';
                    }

                }, '');
            }else{
                $form->select('classify_id','商品分类')->options($options);
            }

            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $form->tags('tag','话题')
                    ->options(['上新','活动','折扣','预售','会员','推荐','特价','京东','淘宝','拼多多', '抖音', '限时', '性价比', '虚拟物品'])
                    ->help('使用，隔开 建议添加1～3个话题');
            }

            $form->multipleSelect('service_id','服务')
                ->options(WxShopService::pluck('name','id'));

            $form->multipleImage('pic', '图片')->uniqueName()->url('files/uploads')->uniqueName()
                ->autoUpload()->sortable();

            $sku_params = [];
            $form->sku('sku', json_encode($sku_params))->display(true)->customFormat(function ($value) use ($form){
                if($value){
                    // 这里是给sku喂数据， 数据格式为
                    $data = (new WxShopGoods())->where('id',$form->getKey())->value('sku');
                    if($data){
                        if($form->isEditing()){
                            $goods_id = $form->model()->id;
                            $data = json_decode($data, true);
                            if($data){
                                $sku_arr = $data['sku'];
                                $attrs_arr = $data['attrs'];
                                if($sku_arr){
                                    for ($i = 0; $i < count($sku_arr); $i++){

                                        $attr_arr = [];
                                        foreach (array_keys($sku_arr[0]) as $key){
                                            if($key == 'pic' || $key == 'stock' || $key == 'vip_price' || $key == 'price'){
                                                continue;
                                            }
                                            $attr_arr[] = $key;
                                        }
                                        $attr_key = '';
                                        if($attr_arr){
                                            foreach ($attr_arr as $attr){
                                                if(!_empty_($attr_key)){
                                                    $attr_key .= '_';
                                                }
                                                $attr_key .= $sku_arr[$i][$attr];
                                            }
                                        }

                                        $stock = WxShopGoodsProduct::where('goods_id', $goods_id)->where('param_value', $attr_key )->value('stock');
                                        $data['sku'][$i]['stock'] = $stock;
                                    }
                                }
                            }
                        }
                    }


                    return json_encode($data);
                }
                return null;
            });
            $form->radio('type')->default(0)->options(FieldUtils::getShopGoodTypes())->when(0, function (Form $form) use ($sku_params) {

            })->when(1, function (Form $form){
                $form->url('url')->help('普通商品留空，淘客链接填在这里，存在链接的商品无法被购买');
            })->when(2, function (Form $form) use ($res11, $modle){
                if($form->isCreating()){
                    $form->textarea('paid_content1', '虚拟付费内容')->help($res11['text'].'用户支付的订单中包含虚拟物品时，订单会增加一个按钮[查看虚拟物品]，如果该次订单全部都是虚拟物品，则会自动改变订单为【已发货】状态');
                }else{
                    $form->textarea('paid_content1', '虚拟付费内容')->help($res11['text'].'用户支付的订单中包含虚拟物品时，订单会增加一个按钮[查看虚拟物品]，如果该次订单全部都是虚拟物品，则会自动改变订单为【已发货】状态')->value($modle->paid_content);
                }

            })->when(3, function (Form $form) use ($res11){
                $form->url('download_url')->help($res11['text'].'https://开头可访问地址');
                $form->text('download_version')->help('编辑修改版本号后，会通知已经购买过的用户');
            })->when(4, function (Form $form) use ($res11, $modle){
                $form->html(function (){
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">卡密一行一个，每次用户购买后，若卡密全部消耗完毕，则会发送消息提示管理员，并下架该商品</div>';
                }, '');
                if($form->isCreating()) {
                    $form->textarea('paid_content2', '卡密')->help($res11['text'] . '用户支付的订单中包含虚拟物品时，订单会增加一个按钮[查看卡密]，如果该次订单全部都是虚拟物品，则会自动改变订单为【已发货】状态');
                }else{
                    $form->textarea('paid_content2', '卡密')->help($res11['text'] . '用户支付的订单中包含虚拟物品时，订单会增加一个按钮[查看卡密]，如果该次订单全部都是虚拟物品，则会自动改变订单为【已发货】状态')->value($modle->paid_content);
                }
            })->when(5, function (Form $form) use ($res11, $modle, $__MINI_GLOBAL_CURRENT_USER_ID__,$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                    $arr = WxShopContact::pluck('address_name', 'id');
                }else{
                    $arr = WxShopContact::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->pluck('address_name', 'id');
                }
                $form->select('contact_id')->options($arr)->help('若没有地址可选，请去前端【我->左侧栏->管理店铺->经营地址->去添加】');
                $form->text('scanners')->help('输入员工在前端的uid，多个用英文逗号隔开');
            })->required();

            if(__system_is_model_enable('laradocs', 'dcat-neditor')){
                $form->neditor('content');
            }else{
                $form->editor('content');
            }

            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $form->multipleSelectTable('question_id')
                    ->title('帮助问题库')
                    ->max(1)
                    ->from(QuestionRender::make())
                    ->model(WxQuestion::class, 'id', 'title', 'selectTable:WxShopGoodsController:question_id');
            }

            $form->number('can_purchase_times')->help('若每人限购一次，已经购买的用户不会在商品详情页显示[加入购物车]')->default(0);

            $res23 = __system__paycode__tip__(23);
            Tooltip::make('.mini_global_admin_open_not_support_tip')
                ->bottom()
                ->title($res23['tip']);


            $users_ledger_flag = false;
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if($__MINI_GLOBAL_PAYCODE_23__){
                    $users_ledger_flag = true;
                }
            }else{
                $users_ledger_flag = true;
            }

            if($users_ledger_flag){
                $form->html(function () use ($res23){
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$res23['text'].'注意：
<br>1、是根据订单价格分账，所以请自己计算好利润，用户下单后，分账用户获得的分账会进入冻结中，在确认收货后，会自动解冻。
<br>2、请勿随意设置百分比，因为我们所有商品都是自营，用户分账剩下的才是平台所得，如果你设置分账总和超过100，那么平台会亏损
<br>3、若用户退款，则冻结的余额会被删除</div>';
                }, '');
                $form->table('users_ledger','分账用户', function (NestedForm $table) {
                    $table->select('user_id', '用户')->options(function ($id) {
                        if($id){
                            $user = \App\Models\User\WxUser::find($id);
                            if ($user) {
                                return [$user->id => $user->user_name];
                            }
                        }
                    })->ajax('select/users')->required();
                    $table->rate('rate', '百分比');
                });
                $form->divider();
            }


            $form->text('guest_present')->help('填嘉宾的用户id，用英文逗号隔开');
//            $form->multipleSelect('guest_present')->options(function ($ids) {
//                if($ids){
//                    $res = [];
//                    foreach ($ids as $id){
//                        $user = \App\Models\User\WxUser::find($id);
//                        if ($user) {
//                            $res[$user->id] = $user->user_name;
//                        }
//                    }
//                    return $res;
//                }
//            })->ajax('select/users')->help('在商品详情页可以展示几个用户');

            $form->divider();

            $form->html(function () use ($res23){
                return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">时间仅仅起提示作用，为用户展示您的服务时间，无实际作用，一般与核销一同使用</div>';
            }, '');
            $form->dateRange('service_date_start', 'service_date_end', '服务日期')->help('如果您的服务日期是每天，则留空，如果不是日期范围，而是具体的某一天，则只用配置开始日期');
            $form->timeRange('service_time_start', 'service_time_end', '服务时间')->help('如果您的服务时间是全天，则留空');

            $form->divider();

            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $form->text('views')->default(0);
                $form->text('buys')->default(0);
                $form->number('sort');
            }

//            $form->switch('is_inspiration');
            $form->switch('state')->default(1);
            $form->datetime('last_sales_at')->default('2099-01-01 00:00:00');

            if ($form->isEditing()) {
                $id = $form->getKey();
                $form->action('shop/save_goods/'.$id);
            }else{
                $form->action('shop/add_goods');
            }
        });
    }

    function isValidDateTime($dateTime) {
        $format = 'Y-m-d H:i:s';
        $d = DateTime::createFromFormat($format, $dateTime);
        return $d && $d->format($format) == $dateTime;
    }

    public function safe_add(Request $request){
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        $__MINI_GLOBAL_IS_ADMIN_SUPER__ = true;
        $collect_from_url = _empty_default_($request->collect_from_url, '');
        if(_empty_($collect_from_url)){
            return JsonResponse::make()->warning('未提交collect_from_url字段值');
        }
        $exists = WxShopGoods::where('collect_from_url', $collect_from_url)->first();
        if($exists){
            return JsonResponse::make()->warning('collect_from_url已经存在对应的商品，商品id为：'.$exists->id);
        }
        return $this->add($request);
    }


    public function add(Request $request){
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__,$__MINI_GLOBAL_PAYCODE_23__,$__MINI_GLOBAL_CURRENT_USER_ID__;
        $input = $request->all();
        $collect_from_url = _empty_default_($request->collect_from_url, '');
        if(_empty_($input['last_sales_at'])){
            $input['last_sales_at'] = '2099-01-01 00:00:00';
        }
        if($this->isValidDateTime($input['last_sales_at'])){

        }else{
            $input['last_sales_at'] = '2099-01-01 00:00:00';
        }

        if($input['type'] == 2 || $input['type'] == 4){
            global $__MINI_GLOBAL_PAYCODE_11__;
            if(!$__MINI_GLOBAL_PAYCODE_11__){
                return JsonResponse::make()->warning('虚拟商品功能未解锁');
            }
            if($input['type'] == 2){
                $input['paid_content'] = $input['paid_content1'];
            }else if($input['type'] == 4){
                $input['paid_content'] = $input['paid_content2'];
            }
        }else{
            $input['paid_content'] = '';
        }

        foreach (['service_date_start','service_date_end','service_time_start','service_time_end'] as $key){
            if(_empty_($input[$key])){
                $input[$key] = null;
            }
        }
        if($input['service_date_end']){
            if($input['service_date_start'] >= $input['service_date_end']){
                $input['service_date_end'] = null;
                $input['service_date_start'] = null;
            }
        }
        if(_empty_($input['service_date_start'])){
            $input['service_date_end'] = null;
        }
        if(_empty_($input['service_time_start']) || $input['service_time_start'] > $input['service_time_end']){
            $input['service_time_end'] = null;
            $input['service_time_start'] = null;
        }

        $guest_present = _empty_default_($input['guest_present'], '');
        if(is_string($guest_present)){
            $guest_present = explode(',', $guest_present);
        }
        if(is_array($guest_present)){
            $guest_present = array_values($guest_present);
            if($guest_present){
                if(_empty_(end($guest_present))){
                    array_pop($guest_present);
                }
                foreach ($guest_present as $gid){
                    if(!(WxUser::where('id', $gid)->exists())){
                        return JsonResponse::make()->error('您配置的嘉宾不存在');
                    }
                }
            }else{
                $guest_present = [];
            }
        }else{
            $guest_present = [];
        }
        if(_empty_($guest_present)){
            $guest_present = [];
        }

        if($input['type'] == 5){
            if(_empty_(_array_key($input, 'contact_id', 0))){
                return JsonResponse::make()->error('核销类商品必须添加经营地址');
            }
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if(WxShopContact::where('id', $input['contact_id'])->value('user_id') != $__MINI_GLOBAL_CURRENT_USER_ID__){
                    return JsonResponse::make()->error('您添加的经营地址不属于您');
                }
            }

            if(!_empty_(_array_key($input, 'scanners', ''))){
                $input['scanners'] = trim($input['scanners'], ',');
                $scanners_arr = explode(',', $input['scanners']);
                foreach ($scanners_arr as $scanner){
                    if(!(WxUser::where('id', $scanner)->exists())){
                        return JsonResponse::make()->error('您添加的核销员，uid为'.$scanner.'实际不存在');
                    }
                }
            }
        }else{
            $input['contact_id'] = null;
            $input['scanners'] = '';
        }

        if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
            $tag = $input['tag'];
            unset($tag[count($tag)-1]);
        }else{
            $tag = [];
        }


        $service = $input['service_id'];
        unset($service[count($service)-1]);

        $options = AdminUtils::get_admin_user_shop_classifys();
        if(_empty_($options)){
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                return JsonResponse::make()->error('当前没有第3层级的商品分类，无法新增商品');
            }else{
                return JsonResponse::make()->error('当前后台账号无绑定的店铺，无法新增商品');
            }
        }else if(!in_array(_array_key($input, 'classify_id', 0), array_keys($options))){
            return JsonResponse::make()->error('店铺的经营分类未包含当前所选的商品分类');
        }

        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            $shop = AdminUtils::get_admin_shop();
            if($shop->margin_rest < $shop->margin_least){
                return JsonResponse::make()->error('您店铺的保证金不足，无法发布新商品');
            }
        }


        $users_ledger_flag = false;
        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            if($__MINI_GLOBAL_PAYCODE_23__){
                $users_ledger_flag = true;
            }
        }else{
            $users_ledger_flag = true;
        }
        if($users_ledger_flag){
            $users_ledger = AdminUtils::_table_data($request->input('users_ledger'));
        }else{
            $users_ledger = '[]';
        }
        $credit_type = $input['credit_type'] == 1 ? 1 : 0;
        DB::beginTransaction();
        try {
            // todo:
            $GoodsModel = new WxShopGoods();
            $GoodsModel->type = $input['type'];
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
                    $GoodsModel->user_id = $__MINI_GLOBAL_CURRENT_USER_ID__;
                    $GoodsModel->shop_id = WxUser::where('id', $__MINI_GLOBAL_CURRENT_USER_ID__)->value('shop_id');
                }
            }
            $GoodsModel->name = $input['name'];
            $GoodsModel->pic = $input['pic'];
            $GoodsModel->vip_price = $credit_type == 1 ? $input['vip_price'] : (int)$input['vip_price'];
            $GoodsModel->price = $credit_type == 1 ? $input['price'] : (int)$input['price'];
            $GoodsModel->credit_type = $credit_type;
            $GoodsModel->classify_id = $input['classify_id'];
            $GoodsModel->content = $input['content'];
            $GoodsModel->views = $__MINI_GLOBAL_IS_ADMIN_SUPER__ ? ($input['views'] ?: 0) : 0;
            $GoodsModel->buys = $__MINI_GLOBAL_IS_ADMIN_SUPER__ ? ($input['buys'] ?: 0 ) : 0;
            $GoodsModel->state = $input['state'];
            $GoodsModel->sku = $input['sku'];
            $GoodsModel->contact_id = $input['contact_id'];
            $GoodsModel->scanners = $input['scanners'];
            $GoodsModel->url = $input['url'];

            $GoodsModel->download_version = $input['download_version'];
            $GoodsModel->download_url = $input['download_url'];
            $GoodsModel->question_id = $__MINI_GLOBAL_IS_ADMIN_SUPER__ ? $input['question_id'] : 0;
            $GoodsModel->can_purchase_times = $input['type'] == 1 ? 0 : $input['can_purchase_times'];

            $GoodsModel->paid_content = $input['paid_content'];
            $GoodsModel->intro = $input['intro'];
            $GoodsModel->service_id = json_encode($service);

            if($users_ledger){
                $GoodsModel->users_ledger = $users_ledger;
            }

            $GoodsModel->tag = json_encode($tag);

            $GoodsModel->last_sales_at = $input['last_sales_at'];
            if($guest_present){
                $GoodsModel->guest_present = implode(',', $guest_present);
            }

            if(!_empty_($input['service_date_start'])){
                $GoodsModel->service_date_start = $input['service_date_start'];
            }
            if(!_empty_($input['service_date_end'])){
                $GoodsModel->service_date_end = $input['service_date_end'];
            }
            if(!_empty_($input['service_time_start'])){
                $GoodsModel->service_time_start = $input['service_time_start'];
            }
            if(!_empty_($input['service_time_end'])){
                $GoodsModel->service_time_end = $input['service_time_end'];
            }

            if($collect_from_url){
                $GoodsModel->collect_from_url = $collect_from_url;
            }

            $GoodsModel->save();

            $goods_id = $GoodsModel->id;

            // 保存产品

            $params = json_decode($input['sku'],true);

            $sku = $params['sku'];
            $attrs = $params['attrs'];
            $attrsArr = array_values($attrs);
            $attrsArr = $this->brush([],$attrsArr);

            $productData = [];
            foreach ($attrsArr as $k=>$v){
                if($credit_type == 1){
                    if(_empty_($sku[$k]['vip_price']) || _empty_($sku[$k]['price'])){
                        DB::rollBack();
                        return JsonResponse::make()->error('SKU未设置价格！');
                    }
                }else{
                    if(_empty_((int)$sku[$k]['vip_price']) || _empty_((int)$sku[$k]['price'])){
                        DB::rollBack();
                        return JsonResponse::make()->error('SKU未设置价格！');
                    }
                }
                $productData[] = [
                    'goods_id' => $goods_id,
                    'vip_price'=>$credit_type == 1 ? $sku[$k]['vip_price'] : (int)$sku[$k]['vip_price'],
                    'price'=>$credit_type == 1 ? $sku[$k]['price'] : (int)$sku[$k]['price'],
                    'stock'=>$sku[$k]['stock'],
                    'pic'=>$sku[$k]['pic'] ?? $input['pic'],
                    'param_value'=>$v,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'credit_type' => $credit_type
                ];
            }
            (new WxShopGoodsProduct())->batchAdd($productData);
            DB::commit();
            return JsonResponse::make()->success('成功！')->redirect('shop/goods');
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return JsonResponse::make()->error('保存出错！');
        }
    }

    public function delte_goods_product($goods_id){

        $product_ids = WxShopGoodsProduct::where('goods_id',$goods_id)->pluck('id')->toArray();
        if(_empty_($product_ids)){
            $product_ids = [];
        }

        $app_luck_draw = Settings::get('app_luck_draw', []);
        if($app_luck_draw){
            $luck_draw_flag = false;
            $luck_dray_names = [];
            $app_luck_draw_new = [];
            $app_luck_draw_disable = [];
            for ($i = 0; $i < count($app_luck_draw); $i ++){
                if($app_luck_draw[$i]['type'] == 3){
                    if(in_array(_array_key($app_luck_draw[$i], 'product', 0), $product_ids)){
                        $luck_draw_flag = true;
                        $luck_dray_names[] = $app_luck_draw[$i]['name'];
                        $app_luck_draw[$i]['product'] = '';
                        $app_luck_draw_disable[] = $app_luck_draw[$i];
                        continue;
                    }
                }
                $app_luck_draw_new[] = $app_luck_draw[$i];
            }
            if($luck_draw_flag){
                Settings::set('app_luck_draw', json_encode($app_luck_draw_new), true);
                UserUtils::assistant_notice('admin', '你配置的抽奖转盘中，存在商品规格['.implode('，',$luck_dray_names).']失效，原因是你修改了原商品，需要你在后台重新配置，原配置请看下方提示, 点击可前往<a href="/pagesB/luckdraw/luckdraw">抽奖页面</a>');
                foreach ($app_luck_draw_disable as $item){
                    UserUtils::assistant_notice('admin', 'id: '.$item['id'].'<br/>'. '图片：'.$item['img'].'<br/>'. '奖项名称：'.$item['name'].'<br/>'. '权重：'.$item['weight'].'<br/>'. '奖励类型：'.$item['type'].'<br/>'. '奖励数量：'.$item['num']);
                }
            }
        }

        WxShopGoodsProduct::where('goods_id',$goods_id)->delete();
        WxShopCart::where('goods_id', $goods_id)->where('state', 0)->update(['state'=>3]);

    }

    public function safe_save(Request $request,$goods_id){
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        $__MINI_GLOBAL_IS_ADMIN_SUPER__ = true;
        return $this->save($request, $goods_id);
    }


    public function save(Request $request,$goods_id){
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__,$__MINI_GLOBAL_PAYCODE_23__,$__MINI_GLOBAL_CURRENT_USER_ID__;
        $input = $request->all();

        if(_empty_($input['last_sales_at'])){
            $input['last_sales_at'] = '2099-01-01 00:00:00';
        }
        if($this->isValidDateTime($input['last_sales_at'])){

        }else{
            $input['last_sales_at'] = '2099-01-01 00:00:00';
        }


        if($input['type'] == 2 || $input['type'] == 4){
            global $__MINI_GLOBAL_PAYCODE_11__;
            if(!$__MINI_GLOBAL_PAYCODE_11__){
                return JsonResponse::make()->warning('虚拟商品未解锁');
            }
            if($input['type'] == 2){
                $input['paid_content'] = $input['paid_content1'];
            }else if($input['type'] == 4){
                $input['paid_content'] = $input['paid_content2'];
            }
        }else{
            $input['paid_content'] = '';
        }

        foreach (['service_date_start','service_date_end','service_time_start','service_time_end'] as $key){
            if(_empty_($input[$key])){
                $input[$key] = null;
            }
        }
        if($input['service_date_end']){
            if($input['service_date_start'] >= $input['service_date_end']){
                $input['service_date_end'] = null;
                $input['service_date_start'] = null;
            }
        }
        if(_empty_($input['service_date_start'])){
            $input['service_date_end'] = null;
        }
        if(_empty_($input['service_time_start']) || $input['service_time_start'] > $input['service_time_end']){
            $input['service_time_end'] = null;
            $input['service_time_start'] = null;
        }

        $guest_present = _empty_default_($input['guest_present'], []);
        if(is_string($guest_present)){
            $guest_present = explode(',', $guest_present);
        }
        if(is_array($guest_present)){
            $guest_present = array_values($guest_present);
            if($guest_present){
                if(_empty_(end($guest_present))){
                    array_pop($guest_present);
                }
                foreach ($guest_present as $gid){
                    if(!(WxUser::where('id', $gid)->exists())){
                        return JsonResponse::make()->error('您配置的嘉宾不存在');
                    }
                }
            }else{
                $guest_present = [];
            }
        }else{
            $guest_present = [];
        }
        if(_empty_($guest_present)){
            $guest_present = [];
        }

        if($input['type'] == 5){
            if(_empty_(_array_key($input, 'contact_id', 0))){
                return JsonResponse::make()->error('核销类商品必须添加经营地址');
            }
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if(WxShopContact::where('id', $input['contact_id'])->value('user_id') != $__MINI_GLOBAL_CURRENT_USER_ID__){
                    return JsonResponse::make()->error('您添加的经营地址不属于您');
                }
            }
            if(!_empty_(_array_key($input, 'scanners', ''))){
                $scanners_arr = explode(',', $input['scanners']);
                foreach ($scanners_arr as $scanner){
                    if(!(WxUser::where('id', $scanner)->exists())){
                        return JsonResponse::make()->error('您添加的核销员，uid为'.$scanner.'实际不存在');
                    }
                }
            }
        }else{
            $input['contact_id'] = null;
        }


        $options = AdminUtils::get_admin_user_shop_classifys();
        if(_empty_($options)){
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                return JsonResponse::make()->error('当前没有第3层级的商品分类，无法新增商品');
            }else{
                return JsonResponse::make()->error('当前后台账号无绑定的店铺，无法新增商品');
            }
        }else if(!in_array($input['classify_id'], array_keys($options))){
            return JsonResponse::make()->error('店铺的经营分类未包含当前所选的商品分类');
        }

        if($request['_method']){

            if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                $tag = $input['tag'];
                unset($tag[count($tag)-1]);
            }else{
                $tag = [];
            }

            $users_ledger_flag = false;
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if($__MINI_GLOBAL_PAYCODE_23__){
                    $users_ledger_flag = true;
                }
            }else{
                $users_ledger_flag = true;
            }
            if($users_ledger_flag){
                $users_ledger = AdminUtils::_table_data(_array_key($input, 'users_ledger', []));
            }else{
                $users_ledger = '[]';
            }

            DB::beginTransaction();
            $WxShopGoods = WxShopGoods::find($goods_id);
            $credit_type = $WxShopGoods->credit_type;

            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                if($__MINI_GLOBAL_CURRENT_USER_ID__ != $WxShopGoods->user_id){
                    return JsonResponse::make()->error('你不是当前商品的发布者');
                }
            }

            try {
                // todo:
                // 删除原有产品
                $this->delte_goods_product($goods_id);
                $updates = [
                    'type' => $input['type'],
                    'name'=>$input['name'],
                    'pic'=>$input['pic'],
                    'vip_price'=>$input['vip_price'],
                    'price'=>$input['price'],
                    'intro'=>$input['intro'],
                    'content'=>$input['content'],
                    'paid_content'=>$input['paid_content'],
                    'state'=>$input['state'],
                    'sku'=>$input['sku'],
                    'contact_id' => $input['contact_id'],
                    'scanners' => $input['scanners'],
                    'url'=>$input['url'],
                    'download_version'=>$input['download_version'],
                    'download_url'=>$input['download_url'],
                    'question_id'=>$__MINI_GLOBAL_IS_ADMIN_SUPER__ ? $input['question_id'] : 0,
                    'can_purchase_times'=>$input['can_purchase_times'],
                    'tag'=> json_encode($tag),
                    'classify_id'=>$input['classify_id'],
                    'service_id'=>$input['service_id'],
                    'users_ledger' => $users_ledger,
                    'last_sales_at' => $input['last_sales_at'],
                ];
                if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
                    $updates['views'] = $input['views'];
                    $updates['buys'] = $input['buys'];
                }

                if($guest_present){
                    $updates['guest_present'] = implode(',', $guest_present);
                }
                if(!_empty_($input['service_date_start'])){
                    $updates['service_date_start'] = $input['service_date_start'];
                }
                if(!_empty_($input['service_date_end'])){
                    $updates['service_date_end'] = $input['service_date_end'];
                }
                if(!_empty_($input['service_time_start'])){
                    $updates['service_time_start'] = $input['service_time_start'];
                }
                if(!_empty_($input['service_time_end'])){
                    $updates['service_time_end'] = $input['service_time_end'];
                }
                // 更新商品
                (new WxShopGoods())->where('id',$goods_id)
                    ->update($updates);

                $params = json_decode($input['sku'],true);

                $sku = $params['sku'];
                $attrs = $params['attrs'];

                $attrsArr = array_values($attrs);

                $attrsArr = $this->brush([],$attrsArr);

                $productData = [];
                foreach ($attrsArr as $k=>$v){

                    if(_empty_($sku[$k]['vip_price']) || _empty_($sku[$k]['price'])){
                        DB::rollBack();
                        return JsonResponse::make()->error('SKU未设置价格！');
                    }

                    $productData[] = [
                        'goods_id' => $goods_id,
                        'vip_price'=>$sku[$k]['vip_price'],
                        'price'=>$sku[$k]['price'],
                        'stock'=>$sku[$k]['stock'],
                        'pic'=>$sku[$k]['pic'],
                        'param_value'=>$v,
                        'created_at'=>date('Y-m-d H:i:s'),
                        'credit_type' => $credit_type
                    ];

                }
                (new WxShopGoodsProduct())->batchAdd($productData);
                DB::commit();
                return JsonResponse::make()->success('成功！')->redirect('shop/goods');
            } catch (\Exception $e) {
                DB::rollBack();
                _logger_(__file__, __line__, $e->getMessage());
                return JsonResponse::make()->error('保存失败！');
            }
        }


    }



    public function brush($res = [], $arr = [])
    {
        if (_empty_($res)) $res = (array)array_shift($arr);
        if (_empty_($arr)) return $res;
        $current = array_shift($arr); # 接下来要参与计算的一组属性
        $last = [];
        foreach ($res as $row => $row_val) { # 循环上一次已经算出的集合
            foreach ($current as $col => $col_val) {
                $last[] = $row_val . '_' . $col_val;
            }
        }
        return $this->brush($last,$arr); # 递归处理, 直到$arr滚到最后一组属性
    }


    /**
     * 上传商品规格图片
     *
     * @param Request $request
     *
     * @return string[]
     */
    public function skuImage(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');

            $path = UploadHandler::handle($file);

            return ['url' => $path['url']];

//            // 返回格式
//            $disk = Storage::disk('cosv5');
//            $url = 'sku';
//            $res = $disk->put($url, $file);
//            return ['url' => config('filesystems.disks.cosv5.cdn') .'/'. $res];
        }
        return [];
    }
}
